package com.kangfu.api.controller;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kangfu.api.interceptor.AuthorizationInterceptor;
import com.kangfu.api.service.IHuaweiService;
import com.kangfu.api.service.IUserInfoService;
import com.kangfu.common.annotation.IgnoreAuth;
import com.kangfu.common.constant.CacheConstant;
import com.kangfu.common.constant.SystemConstant;
import com.kangfu.common.exception.BusinessException;
import com.kangfu.common.model.AjaxResult;
import com.kangfu.common.utils.RedisUtils;
import com.kangfu.db.domain.entity.User;
import com.kangfu.db.domain.entity.UserInfo;
import com.kangfu.db.domain.entity.UserInfoType;
import com.kangfu.db.mapper.UserInfoMapper;
import com.kangfu.db.mapper.UserMapper;
import com.kangfu.db.model.bo.UserInfoCountBo;
import com.kangfu.db.model.bo.huawei.AccessTokenBo;
import com.kangfu.db.model.request.UserQuestionnaireRequest;
import com.kangfu.db.model.vo.UserInfoVo;
import com.kangfu.db.model.vo.UserQuestionnaireVo;
import com.kangfu.wechat.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.util.Arrays.asList;

@RestController
@RequestMapping("/userinfo")
public class UserInfoController {

    @Autowired
    public RedisUtils redisUtils;

    @Autowired
    public IUserInfoService userInfoService;

    @Autowired
    public IHuaweiService huaweiService;

    @Autowired
    public UserInfoMapper userInfoMapper;

    @Autowired
    public UserMapper userMapper;

    @GetMapping("/detail")
    @CrossOrigin
    public AjaxResult selectByType(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestParam(name = "type") Integer type, @RequestParam(name = "subType", defaultValue = "0") Integer subType) throws JsonProcessingException {
        if (type == null) {
            throw new BusinessException("参数错误");
        }
        UserInfo userInfo = userInfoService.selectByUserIdAndSubType(userId, type, subType);
        if (userInfo == null) {
            return AjaxResult.success();
        }
        UserQuestionnaireVo userQuestionnaireVo = new UserQuestionnaireVo();
        userQuestionnaireVo.setId(userInfo.getId());
        userQuestionnaireVo.setType(userInfo.getType());
        userQuestionnaireVo.setSubType(userInfo.getSubType());

        if (userInfo.getContent() != null && !"".equals(userInfo.getContent())) {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
            Map<String, Object> map = mapper.readValue(userInfo.getContent(), Map.class);
            if (map != null) {
                userQuestionnaireVo.setData(map);
            }
        }

        userQuestionnaireVo.setCreateTime(userInfo.getCreateTime());
        userQuestionnaireVo.setEditable(1);

        return AjaxResult.success(userQuestionnaireVo);
    }

    @PostMapping("/add")
    @CrossOrigin
    public AjaxResult add(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestBody UserQuestionnaireRequest userQuestionnaireRequest) {
        userInfoService.insertUserInfo(userId, userQuestionnaireRequest);
        String url = "";
        //看看是否要进入下一步填写调差问卷的url
        //用户绑定手环流程--签署知情同意书--填写调查问卷--手环绑定
        //type  （1:知情同意书，2:调查问卷）
        Integer type = userQuestionnaireRequest.getType();
        Integer subType = userQuestionnaireRequest.getSubType();
        if (type == 1) {
            //已经填写好了知情同意书，下一步就是填写调查问卷
            url = SystemConstant.API_URL + "/questionaire/question.html?subType=1";
        } else if (type == 2) {
            //填写好了调查问卷，下一步就是填写体适能测试
            //调查问卷有4个步骤
            if (subType == 1) {
                url = SystemConstant.API_URL + "/questionaire/question.html?subType=2";
            } else if (subType == 2) {
                url = SystemConstant.API_URL + "/questionaire/question.html?subType=3";
            } else if (subType == 3) {
                url = SystemConstant.API_URL + "/questionaire/question.html?subType=4";
            } else {
                //填完了调查问卷就去绑定手环
                url = SystemConstant.API_URL + "/huawei/authorize?a=a";
            }
        }
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("url",url);
        return AjaxResult.success(hashMap);
    }

    @PostMapping("/update/{id}")
    @CrossOrigin
    public AjaxResult update(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @PathVariable("id") int id , @RequestBody UserQuestionnaireRequest userQuestionnaireRequest) {
//        userInfoService.updateByUserIdAndType(userId, id, userQuestionnaireRequest); //填了之后不让用户修改
        return AjaxResult.success();
    }


    @GetMapping("/getProgress")
    @CrossOrigin
    public AjaxResult getProgress(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId) {
        HashMap<String, Object> hashMap = new HashMap<>();
        //检查用户是否开放绑定手环
        User user = userMapper.selectUserById(userId);
        //todo 为了演示，这个先不检查
        if (!"1".equals(user.getHuaweiStatus())) {
            throw new BusinessException("您的账号尚未激活，请联系管理人员进行激活");
        }

        //todo 先过华为的检查
        //检查用户调查问卷是否已经填写完毕
        //检查知情同意书是否填写
        UserInfo userInfo = userInfoMapper.selectByUserIdAndSubType(userId, 1, 0);
        if (userInfo == null) {
            hashMap.put("url",SystemConstant.API_URL + "/questionaire/agree.html?subType=0");
            return AjaxResult.success(hashMap);
        }

        //检查调查问卷是否填写
        userInfo = userInfoMapper.selectByUserIdAndSubType(userId, 2,1);
        if (userInfo == null) {
            hashMap.put("url",SystemConstant.API_URL + "/questionaire/question.html?subType=1");
            return AjaxResult.success(hashMap);
        }
        userInfo = userInfoMapper.selectByUserIdAndSubType(userId, 2,2);
        if (userInfo == null) {
            hashMap.put("url",SystemConstant.API_URL + "/questionaire/question.html?subType=2");
            return AjaxResult.success(hashMap);
        }
        userInfo = userInfoMapper.selectByUserIdAndSubType(userId, 2,3);
        if (userInfo == null) {
            hashMap.put("url",SystemConstant.API_URL + "/questionaire/question.html?subType=3");
            return AjaxResult.success(hashMap);
        }
        userInfo = userInfoMapper.selectByUserIdAndSubType(userId, 2,4);
        if (userInfo == null) {
            hashMap.put("url",SystemConstant.API_URL + "/questionaire/question.html?subType=4");
            return AjaxResult.success(hashMap);
        }
        if (1 == user.getVersion()) {
            //检查用户是否绑定手环
            Object object = redisUtils.get(CacheConstant.HUAWEI_ACCESS_TOKEN_PREFIX + userId);
            //从redis中获取accessToken
            AccessTokenBo accessTokenBo = JsonUtil.parseObject(JsonUtil.toJSONString(redisUtils.get(CacheConstant.HUAWEI_ACCESS_TOKEN_PREFIX + userId)), AccessTokenBo.class);
            if (accessTokenBo == null) {
                //redis中没有，那就是要用户授权
                hashMap.put("url",SystemConstant.API_URL + "/huawei/authorize?a=a");
                return AjaxResult.success(hashMap);
            } else {
                //redis中有，那就是有过授权，接下来就检查授权是否完整
                //检查授权是否完整
                if (2 != user.getHuaweiAuthorizeComplete()) {
                    //授权不完整
                    hashMap.put("url",SystemConstant.API_URL + "/huawei/authorize?a=a");
                    hashMap.put("bindUncomplete", 1);
                    return AjaxResult.success(hashMap);
                }
                //检查用户隐私授权状态
                int healthKitPrivacy = huaweiService.checkHealthKitPrivacy(userId);
                if (healthKitPrivacy == 3) {
                    hashMap.put("url",SystemConstant.API_URL + "/huawei/authorize?a=a");
                    return AjaxResult.success(hashMap);
                } else if (healthKitPrivacy == 1) {
                    throw new BusinessException("请在华为运动健康App中开启华为运动健康服务");
                }
            }
        }
        hashMap.put("url","");
        return AjaxResult.success(hashMap);
    }

    @GetMapping("/list")
    @CrossOrigin
    public AjaxResult list(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId) {

        Map<Integer, UserInfoCountBo> userInfoCountBoMap = userInfoMapper.selectCountBoByUserId(userId);

        List<UserInfoType> userInfoTypes = userInfoMapper.selectTypeList();

        List<UserInfoVo> list = new ArrayList<UserInfoVo>();

        List<Integer> subZeroList =  asList(1,3,7,11,15);

        for (UserInfoType userInfoType : userInfoTypes) {
            UserInfoVo userInfoVo = new UserInfoVo();
            userInfoVo.setName(userInfoType.getName());
            String subType = "1";
            if (subZeroList.contains(userInfoType.getId())) {
                subType = "0";
            }
            userInfoVo.setUrl(SystemConstant.API_URL + "/questionaire/"+ userInfoType.getHtmlName() +".html?subType=" + subType);
            //检查是否写完
            if (userInfoCountBoMap == null) {
                userInfoVo.setEditable(1);
                userInfoVo.setIsFinish(0);
                list.add(userInfoVo);
                continue;
            }
            UserInfoCountBo userInfoCountBo = userInfoCountBoMap.get(userInfoType.getId());
            if (userInfoCountBo == null) {
                userInfoVo.setEditable(1);
                userInfoVo.setIsFinish(0);
                list.add(userInfoVo);
                continue;
            }
            Integer count = userInfoCountBo.getNum();
            if (subZeroList.contains(userInfoType.getId())) {
                //只有1个
                if (count == null || count < 1) {
                    //没填写完
                    userInfoVo.setEditable(1);
                    userInfoVo.setIsFinish(0);
                } else {
                    //填写完了
                    userInfoVo.setEditable(0);
                    userInfoVo.setIsFinish(1);
                }
            } else {
                //有4个
                if (count == null || count < 4) {
                    //没填写完
                    userInfoVo.setEditable(1);
                    userInfoVo.setIsFinish(0);
                } else {
                    //填写完了
                    userInfoVo.setEditable(0);
                    userInfoVo.setIsFinish(1);
                }
            }

            list.add(userInfoVo);
        }

        return AjaxResult.success(list);
    }
}
